package com.one.group.admin.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.one.group.admin.mapper.DecorationManagementMapper;
import com.one.group.model.dto.*;
import com.one.group.model.entity.*;
import com.one.group.model.vo.DecorationManagementListVo;
import com.one.group.service.DecorationChargeService;
import com.one.group.service.DecorationManagementService;
import com.one.group.service.DecorationInspectionService;
import cn.hutool.core.convert.Convert;
import com.one.group.service.SpCellService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @author kld
 * @date 2025/10/1
 * @description 装修管理Service实现
 */
@Service
public class DecorationManagementServiceImpl extends ServiceImpl<DecorationManagementMapper, DecorationManagement> implements DecorationManagementService {
    
    @Autowired
    private DecorationChargeService decorationChargeService;
    
    @Autowired
    private DecorationInspectionService decorationInspectionService;
    
    @Autowired
    private SpCellService spCellService;
    
    // 获取租户ID的辅助方法
    private Long getCurrentTenantId() {
        Long tenantId = Convert.toLong(StpUtil.getExtra("tenant_id"));
        return tenantId;
    }

    @Override
    public List<DecorationManagement> findByDecorationQueryDto(DecorationManagementQueryDto queryDto) {
        // 设置租户ID（如果未提供）
        if (queryDto.getTenantId() == null) {
            queryDto.setTenantId(getCurrentTenantId());
        }
        // 直接调用Mapper层的查询方法
        return getMapper().findByDecorationQueryDto(queryDto);
    }
    
    @Override
    public List<DecorationManagementListVo> findDecorationListWithCellName(DecorationManagementQueryDto queryDto) {
        // 设置租户ID（如果未提供）
        if (queryDto.getTenantId() == null) {
            queryDto.setTenantId(Convert.toLong(StpUtil.getExtra("tenant_id")));
        }
        return getMapper().findDecorationListWithCellName(queryDto);
    }
    @Override
    public List<DecorationManagementListVo> findDecorationListByQueryDto(DecorationQueryDto decorationQueryDto) {
        // 获取当前租户ID
        Long tenantId = getCurrentTenantId();
        decorationQueryDto.setTenantId(tenantId);
        return getMapper().findDecorationListByQueryDto(decorationQueryDto);
    }
    
    @Override
    public DecorationDetailDto getDecorationDetail(Long id) {
        if (id == null) {
            return null;
        }
        
        // 验证是否为当前租户的数据
        Long tenantId = getCurrentTenantId();
        DecorationManagement decorationInfo = getById(id);
        if (decorationInfo == null || decorationInfo.getIsDeleted() != 0 || !tenantId.equals(decorationInfo.getTenantId())) {
            return null;
        }
        
        DecorationDetailDto detailDto = new DecorationDetailDto();
        detailDto.setDecorationInfo(decorationInfo);
        
        // 获取验收信息
        DecorationInspection inspectionInfo = decorationInspectionService.findByDecorationId(id);
        detailDto.setInspectionInfo(inspectionInfo);
        
        return detailDto;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean addDecoration(DecorationManagement decorationManagement) {
        // 设置租户ID
        Long tenantId = getCurrentTenantId();
        decorationManagement.setTenantId(tenantId);
        decorationManagement.setCreateTime(new Date());
        decorationManagement.setUpdateTime(new Date());
        decorationManagement.setIsDeleted(0);
        decorationManagement.setStatus("待审核"); // 默认为待审核状态
        return save(decorationManagement);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean updateDecoration(DecorationManagement decorationManagement) {
        // 验证是否为当前租户的数据
        Long tenantId = getCurrentTenantId();
        DecorationManagement existing = getById(decorationManagement.getId());
        if (existing == null || !tenantId.equals(existing.getTenantId())) {
            return false;
        }
        decorationManagement.setTenantId(tenantId); // 确保租户ID不变
        decorationManagement.setUpdateTime(new Date());
        return updateById(decorationManagement);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean deleteDecoration(Long id) {
        // 验证是否为当前租户的数据
        Long tenantId = getCurrentTenantId();
        DecorationManagement existing = getById(id);
        if (existing == null || !tenantId.equals(existing.getTenantId())) {
            return false;
        }
        DecorationManagement decoration = new DecorationManagement();
        decoration.setId(id);
        decoration.setIsDeleted(1);
        decoration.setUpdateTime(new Date());
        return updateById(decoration);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean batchDelete(List<Long> ids) {
        for (Long id : ids) {
            if (!deleteDecoration(id)) {
                return false;
            }
        }
        return true;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean approveDecoration(Long id, String status, String approver) {
        // 验证是否为当前租户的数据
        Long tenantId = getCurrentTenantId();
        DecorationManagement existing = getById(id);
        if (existing == null || !tenantId.equals(existing.getTenantId())) {
            return false;
        }
        DecorationManagement decoration = new DecorationManagement();
        decoration.setId(id);
        decoration.setStatus(status);
        decoration.setApprover(approver);
        decoration.setUpdateTime(new Date());
        
        // 如果审核通过，设置为待装修状态
        if ("待装修".equals(status)) {
            decoration.setConstructionStartTime(new Date());
        }
        
        return updateById(decoration);
    }
    
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean inspectDecoration(Long id, String inspector, String inspectionResult, String inspectionNotes) {
        // 调用带照片URL的方法，照片URL为null
        return inspectDecoration(id, inspector, inspectionResult, inspectionNotes, null);
    }
    
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean inspectDecoration(Long id, String inspector, String inspectionResult, String inspectionNotes, String inspectionPhotosUrl) {
        // 参数验证
        if (id == null || inspector == null || inspectionResult == null) {
            return false;
        }
        
        // 验证是否为当前租户的数据
        Long tenantId = getCurrentTenantId();
        DecorationManagement existing = getById(id);
        if (existing == null || !tenantId.equals(existing.getTenantId())) {
            return false;
        }
        
        // 更新装修状态为已验收
        DecorationManagement decoration = new DecorationManagement();
        decoration.setId(id);
        decoration.setStatus("已验收");
        decoration.setConstructionEndTime(new Date());
        decoration.setUpdateTime(new Date());
        
        boolean result = updateById(decoration);
        if (!result) {
            return false;
        }
        
        // 创建并保存验收记录
        DecorationInspection inspection = new DecorationInspection();
        inspection.setDecorationId(id);
        inspection.setInspector(inspector);
        inspection.setInspectionResult(inspectionResult);
        inspection.setInspectionNotes(inspectionNotes);
        inspection.setInspectionPhotosUrl(inspectionPhotosUrl);
        inspection.setTenantId(tenantId); // 设置租户ID
        
        return decorationInspectionService.saveDecorationInspection(inspection);
    }
    
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean inspectDecoration(Long id) {
        // 验证是否为当前租户的数据
        Long tenantId = getCurrentTenantId();
        DecorationManagement existing = getById(id);
        if (existing == null || !tenantId.equals(existing.getTenantId())) {
            return false;
        }
        DecorationManagement decoration = new DecorationManagement();
        decoration.setId(id);
        decoration.setStatus("已验收");
        decoration.setConstructionEndTime(new Date());
        decoration.setUpdateTime(new Date());
        return updateById(decoration);
    }
    
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean addDecorationWithCharges(DecorationApplicationDto applicationDto) {
        if (applicationDto == null) {
            return false;
        }
        
        // 转换DTO为实体对象
        DecorationManagement decorationManagement = new DecorationManagement();
        decorationManagement.setCellId(applicationDto.getCellId());
        decorationManagement.setHouseNumber(applicationDto.getHouseNumber());
        decorationManagement.setDecorationCompany(applicationDto.getDecorationCompany());
        decorationManagement.setApplicant(applicationDto.getApplicant());
        decorationManagement.setApplicantPhone(applicationDto.getApplicantPhone());
        decorationManagement.setApprover(applicationDto.getApprover());
        decorationManagement.setConstructionUnit(applicationDto.getConstructionUnit());
        decorationManagement.setDecorationContent(applicationDto.getDecorationContent());
        decorationManagement.setDecorationDeposit(applicationDto.getDecorationDeposit());
        decorationManagement.setDecorationDrawingsUrl(applicationDto.getDecorationDrawingsUrl());
        decorationManagement.setRejectReason(applicationDto.getRejectReason());
        decorationManagement.setRemark(applicationDto.getRemark());
        decorationManagement.setResponsiblePerson(applicationDto.getResponsiblePerson());
        decorationManagement.setResponsiblePhone(applicationDto.getResponsiblePhone());
        decorationManagement.setStatus(applicationDto.getStatus() != null ? applicationDto.getStatus() : "待审核");
        decorationManagement.setTotalFee(applicationDto.getTotalFee());

        // 调用现有的addDecoration方法保存装修信息
        boolean saveSuccess = addDecoration(decorationManagement);
        
        if (!saveSuccess || decorationManagement.getId() == null) {
            return false;
        }
        
        // 保存收费标准信息
        if (applicationDto.getChargeStandards() != null && !applicationDto.getChargeStandards().isEmpty()) {
            Long decorationId = decorationManagement.getId();
            Long tenantId = getCurrentTenantId();
            Date now = new Date();
            
            for (DecorationChargeItemDto chargeItem : applicationDto.getChargeStandards()) {
                if (chargeItem == null || chargeItem.getId() == null) {
                    continue;
                }
                
                DecorationCharge decorationCharge = new DecorationCharge();
                decorationCharge.setDecorationId(decorationId);
                decorationCharge.setChargeStandardId(chargeItem.getId());
                decorationCharge.setQuantity(chargeItem.getQuantity());
                decorationCharge.setTenantId(tenantId);

                decorationChargeService.saveDecorationCharge(decorationCharge);
            }
        }
        
        return true;
    }
}